// 获取应用实例
const app = getApp()
let plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager() //录音组件
let innerAudioContext = wx.createInnerAudioContext() //播音组件
let dateTimePicker = require('../../utils/dateTimePicker');
let uuidGen = require('../../utils/_uuid');
let request = require('../../utils/_request');
// 全局变量
const {
  baseUrl,
  audioManager
} = getApp().globalData
console.log('baseUrl', baseUrl)


Page({
  data: {
    userInfo: getApp().globalData.userInfo,
    phoneNum: getApp().globalData.phoneNum,
    uuid: {
      image: '',
      video: '',
      audio: '',
    },
    // 上报事件列表数据
    eventData: {
      total: 0,
      pageNum: 1,
      pageSize: 10,
      list: [],
      isRefreshing: false
    },
    // 控件
    options: {
      showPopup: false,
      currentClickItem: '',
      maxPhotoCount: 4,
      maxVideoCount: 2,
      maxRecordCount: 3,
      recordStatus: [0, 0, 0] //-1暂停,1播放中,0一般
    },
    // 表单数据
    formData: {
      source: '大联动',
      eventName: '',
      eventType: [],
      text: '',
      address: '',
      level: '一般',
      time: '',
      appealUser: '',
      appealPhoneNum: '',
    },
    // 事件类别
    eventType: {
      selectedIndex: [],
      objectItems: [],
      data: null
    },

    level: ['一般', '急', '特急'],
    source: ['大联动', '市长公开电话'],
    photosList: [],
    videosList: [],
    recordList: [],
    dateTimeArray: null,
    dateTime: null,
    startYear: 2000,
    endYear: 2050,
  },
  onLoad() {
    this.initUuid()
    this.initTimePicker()
    this.initRecord()
    this.getDictInfo()
    this.getEventList()
    // this.initEventPicker()
    let that = this
    getApp().watchUserInfo(that.watchBackUserInfo)
    getApp().watchPhoneNum(that.watchBackPhoneNum)
  },
  watchBackUserInfo(userInfo) {
    console.log('监听到的数据userInfo：' + userInfo)
    let that = this
    that.setData({
      userInfo: userInfo
    })
  },
  watchBackPhoneNum(phoneNum) {
    console.log('监听到的数据phoneNum：' + phoneNum)
    let that = this
    that.setData({
      phoneNum: phoneNum
    })
  },
  // 详情
  goDetail(e, cid) {
    let id = e ? e.currentTarget.dataset.id : cid
    wx.navigateTo({
      url: '../detail/detail?id=' + id
    })
  },
  // 切换向上弹窗
  togglePopup(e) {
    let {
      options
    } = this.data
    if (e.target.dataset.name) {
      options.currentClickItem = e.target.dataset.name
    }
    options.showPopup = !options.showPopup
    this.setData({
      options
    })
  },

  // 文本双向绑定
  setFormValue(e) {
    let {
      formData,
      options
    } = this.data
    console.log(e.target)
    console.log(e.detail.value)
    formData[e.target.dataset.name] = e.detail.value
    options.showPopup = false
    this.setData({
      formData,
      options
    })
  },
  // 选择框双向绑定
  // bindPickerChange(e) {
  //   let formData = this.data.formData
  //   let objectArray = this.data[e.target.dataset.optionsName]
  //   formData[e.target.dataset.name] = objectArray[e.detail.value].id
  //   formData[e.target.dataset.name + 'Label'] = objectArray[e.detail.value].name
  //   this.setData({
  //     formData
  //   })
  // },

  // 选择媒体文件
  bindChooseFile(e) {
    let {
      file
    } = e.detail
    const {
      uuid
    } = this.data
    const {
      name: type
    } = e.target.dataset
    if (type === 'image') {
      let index = this.data.photosList.length
      let photosList = this.data.photosList.concat(file)
      this.setData({
        photosList
      })
      this.uploadFile(photosList, index, uuid.image, 0)
    } else if (type === 'video') {
      let index = this.data.videosList.length
      let videosList = this.data.videosList.concat(file)
      this.setData({
        videosList
      })
      this.uploadFile(videosList, index, uuid.video, 1)
    }
  },
  // 删除文件
  bindDeleteFile(e) {
    let that = this
    const {
      photosList,
      videosList
    } = this.data
    const {
      name: type
    } = e.target.dataset
    wx.showModal({
      title: "提示",
      content: "是否删除",
      success: function (res) {
        if (res.confirm) {
          if (type === "image") {
            photosList.splice(e.detail.index, 1)
            that.setData({
              photosList
            })
          } else if (type === "video") {
            videosList.splice(e.detail.index, 1)
            that.setData({
              videosList
            })
          }
        } else if (res.cancel) {
          console.log("用户点击取消")
        }
      }
    })
  },
  bindPickerChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log('dataset', e.currentTarget)
    let targetName = e.currentTarget.dataset.name
    let {
      formData
    } = this.data
    formData[targetName] = this.data[targetName][e.detail.value]
    this.setData({
      formData
    })
  },
  /**
   * 类型选择确认
   */
  typePickerConfirmed(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let {
      eventType,
      formData
    } = this.data
    let parentType = eventType.objectItems[0]
    let childType = eventType.objectItems[1]
    eventType.selectedIndex = e.detail.value
    formData.eventType = [parentType[e.detail.value[0]], childType[e.detail.value[1]]].map(i => i.dictDesc)
    console.log(eventType,
      formData)
    this.setData({
      eventType,
      formData
    })
  },
  /**
   * 事件类型变更联动
   * @param {*} e
   */
  typePickerChanged(e) {
    //console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let changedColumn = e.detail.column //修改的列
    let changedIndex = e.detail.value //修改的下标
    let eventType = this.data.eventType
    let typeData = eventType.data
    let typeIndex = eventType.selectedIndex
    typeIndex[changedColumn] = e.detail.value; //修改为新的下标

    //修改的是第一列
    if (changedColumn === 0) {
      eventType.objectItems[changedColumn + 1] = typeData[changedIndex].child
      typeIndex[changedColumn + 1] = 0
    }

    this.setData({
      eventType,
      // typeIndex
    })
  },
  // 初始化时间picker
  initTimePicker() {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray
    });
  },
  // 双向绑定日期时间控件
  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
    let dateTimeArray = this.data.dateTimeArray
    let dateTime = this.data.dateTime
    let time = dateTimeArray[0][dateTime[0]] + '-' + dateTimeArray[1][dateTime[1]] + '-' + dateTimeArray[2][dateTime[2]] + ' ' + dateTimeArray[3][dateTime[3]] + ':' + dateTimeArray[4][dateTime[4]] + ':' + dateTimeArray[5][dateTime[5]]
    let formData = this.data.formData
    formData[e.target.dataset.name] = time
    this.setData({
      formData
    })
  },
  // 日期时间列选择变化
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },
  getMap() {
    let that = this
    wx.chooseLocation({
      success: function (res) {
        let name = res.name
        let address = res.address
        let latitude = res.latitude
        let longitude = res.longitude
        let formData = that.data.formData
        formData.address = res.address
        that.setData({
          formData
        })
        console.log(res)
      }
    })
  },
  /*
  文件上传
  */
  uploadFile(fileList, index, uuid, type) {
    let that = this
    let path = fileList[index].path || fileList[index].url
    wx.uploadFile({
      url: baseUrl + '/api/file/uploadFile',
      filePath: path,
      name: 'file',
      formData: {
        //上传数据
        uuid: uuid,
        file: path,
        type: type
      },
      success(res) {
        // set.setData({
        //   'TIP': '第' + (index + 1) + '个文件上传成功'
        // });
        if (index + 1 == fileList.length) {
          // wx.showModal({
          //   title: '提示',
          //   content: '上传成功',
          //   success: function (res) {
          //   }
          // })
        } else {
          that.uploadFile(fileList, index + 1, uuid, type);
        }
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '上传失败，请删除',
          showCancel: false,
          success: function (res) {}
        })
      }
    })
  },

  // 录音
  streamRecord() {
    if (this.data.recordList.length < this.data.options.maxRecordCount) {
      manager.start({
        duration: 60000,
        lang: "zh_CN"
      })
    } else {
      wx.showToast({
        title: '语音文件超限',
        icon: 'error'
      })
    }
  },
  streamRecordEnd() {
    manager.stop()
  },
  // 删除录音
  deleteRecord(e) {
    let {
      recordList,
      options
    } = this.data
    let index = e.currentTarget.dataset.index
    recordList.splice(index, 1)
    // options.recordStatus.splice(index, 1)
    // options.recordStatus.push(0)

    // 暂停播放
    setTimeout(() => {
      options.recordStatus.forEach((c, i, a) => a[i] = 0)
      innerAudioContext.stop()
    }, 100)

    this.setData({
      recordList,
      options
    })
  },
  /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function () {
    let {
      recordList,
      uuid,
      options
    } = this.data
    let that = this
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      console.log("识别内容变化", res)
    }
    manager.onStart = function (res) {
      console.log("成功开始录音识别", res)
      wx.showLoading({
        title: '开始录音',
      })
    }
    // 识别结束事件
    manager.onStop = ({
      tempFilePath,
      duration,
      fileSize,
      result
    }) => {
      console.log(tempFilePath, duration, fileSize, result)
      recordList.push({
        url: tempFilePath,
        size: fileSize,
        duration: (duration / 1000).toFixed(2)
      })
      this.setData({
        recordList
      })
      // 录制一条语音就发送一条语音
      let index = recordList.length - 1
      console.log(recordList, index, uuid.audio, 2)
      that.uploadFile(recordList, index, uuid.audio, 2)
      // toast通知
      wx.hideLoading().then(function () {
        wx.showToast({
          title: '结束录音',
        })
      })
      options.recordStatus.forEach((c, i, a) => a[i] = 0)
      console.log('识别结束：', {
        tempFilePath,
        duration,
        fileSize,
        result
      })
    }

    // 识别错误事件
    manager.onError = (res) => {
      console.log('识别错误' + res)
    }
    // 音频播放开始回调
    innerAudioContext.onPlay(() => {
      // wx.showToast({
      //   title: '开始播放',
      //   duration: 500
      // })
    })
    // 音频播放结束回调
    innerAudioContext.onEnded(() => {
      // innerAudioContext.stop()
      options.recordStatus.forEach((c, i, a) => a[i] = 0)
      this.setData({
        options
      })
    })
  },
  //音频播放
  playAudio(e) {
    let options = this.data.options
    let {
      path: src,
      index
    } = e.currentTarget.dataset

    if (innerAudioContext.src === src && options.recordStatus[index] === 1) {
      // 暂停
      innerAudioContext.pause()
      options.recordStatus.forEach((c, i, a) => a[i] = 0)
      options.recordStatus[index] = -1
    } else {
      // 播放
      innerAudioContext.src = src
      innerAudioContext.play()
      options.recordStatus.forEach((c, i, a) => a[i] = 0)
      options.recordStatus[index] = 1
    }

    this.setData({
      options
    })
  },
  // 获取字典类型
  getDictInfo() {
    let that = this
    let eventType = this.data.eventType
    let formData = this.data.formData
    request.$get({
      url: '/api/dictinfo/list',
      onSuccess(res) {
        let typeData = res.data.list.filter(item => item.dictType === 'sjddl')

        let parentType = []
        let childType
        typeData.forEach((c, i, a) => {
          if (i === 0) {
            childType = c.child
          }
          parentType.push({
            ...c,
            child: null
          })
        })
        eventType = {
          data: typeData,
          objectItems: [parentType, childType],
          selectedIndex: [0, 0]
        }
        formData.eventType = [parentType[0].dictDesc, childType[0].dictDesc]
        that.setData({
          eventType,
          formData
        })
      }
    })
  },

  /**
   * 生成uuid
   * 绑定语音播放开始事件
   */
  initUuid() {
    this.setData({
      uuid: {
        image: uuidGen.uuid(),
        video: uuidGen.uuid(),
        audio: uuidGen.uuid()
      }
    })
  },
  onRefreshList() {
    let {
      eventData
    } = this.data
    if (eventData.isRefreshing) return
    eventData.pageNum = 1
    eventData.isRefreshing = true
    this.setData({
      eventData
    })
    this.getEventList()
  },
  /**
   * 获取上报事件列表
   */
  getEventList() {
    let {
      pageNum,
      pageSize,
      list: oldList
    } = this.data.eventData
    let that = this
    if (pageNum === 1) {
      wx.showLoading({
        title: '加载中...',
      })
      let eventData = this.data.eventData
      eventData.list.length = 0
      that.setData({
        eventData
      })
    }
    request.$get({
      url: '/api/eventinfo/list',
      data: {
        pageNum: pageNum,
        pageSize
      },
      onSuccess(res) {
        let eventData = res.data.page
        eventData.list = oldList.concat(eventData.list)
        eventData.pageNum++
        that.setData({
          eventData
        })
      },
      onFinish(res) {
        let eventData = res.data.page
        eventData.isRefreshing = false
        that.setData({
          eventData
        })
      }
    })

  },
    // 分享
  onShareAppMessage() {
    return {
      title: '数字人慧勤务平台',
      desc: '数字人慧勤务平台',
      path: '/pages/add/add' // 路径，传递参数到指定页面。
    }
  },
  /**
   * 提交表单
   */
  submitForm(e) {
    let that = this
    let {
      uuid,
      formData,
      photosList,
      videosList,
      recordList,
    } = this.data
    let {
      self
    } = e.currentTarget.dataset
    console.log(this.data.formData)
    let uuidList = []
    if (photosList.length) {
      uuidList.push(uuid.image)
    }
    if (videosList.length) {
      uuidList.push(uuid.video)
    }
    if (recordList.length) {
      uuidList.push(uuid.audio)
    }
    wx.showLoading({
      title: '上传中，请稍等',
      icon: 'success',
      mask: true
    })
    request.$post({
      url: '/api/eventinfo/save',
      data: {
        eventtitle: formData.eventName,
        sjddl: formData.eventType[0],
        eventCategory: formData.eventType[1],
        eventNature: formData.level,
        happenTime: formData.time,
        eventAddress: formData.address,
        eventContent: formData.text,
        selfDisposal: +self,
        uuid: uuidList,
        appealUser: formData.appealUser,
        appealPhoneNum: formData.appealPhoneNum,
        appealSource: formData.source
      },
      onSuccess: function (res) {
        console.log(res.data)
        if (res.data.code === 0) {
          wx.showToast({
            title: '事件已上传',
            icon: 'success',
            duration: 2000,
            mask: true,
            success: function () {
              setTimeout(() => {
                that.goDetail(false, res.data.id)
              }, 2000)
            }
          })
        }
      },
    })

  }


})
